// createContext 相当于创建 vue的provide,将组件的属性或方法共享给后代组件
// useReducer 相当于创建 vuex的actions,共享数据的更新
import React, {createContext, useReducer} from 'react';

import Text31 from './test31';   

export const myContext = createContext();  // 创建Context,管理共享数据
const { Provider } = myContext;

const obj = {
    count: 0,
    str: '初始值'
}

const reducer = (state, action)=>{
    console.log('action', action);
    let { type, val } = action;
    let oldState = { ...state };    // 重点
    if(type === 'add'){
        return {
            ...oldState,
            count: oldState.count +1
        };
    }else if(type === 'sub'){
        return {
            ...oldState,
            count: oldState.count -1
        };
    }

    if(type === 'setStr' ){
        return {
            ...oldState,
            str: val
        };
    }

}
const Store = (props)=>{
    const [$store, dispatch] = useReducer(reducer, obj)
    // const [store, dispatch] = useReducer((state, action)=>{
    //     console.log('action', action);
    //     let { type, val } = action;
    //     let oldState = { ...state };    // 重点
    //     if(type === 'add'){
    //         return {
    //             ...oldState,
    //             count: oldState.count +1
    //         };
    //     }else if(type === 'sub'){
    //         return {
    //             ...oldState,
    //             count: oldState.count -1
    //         };
    //     }

    //     if(type === 'setStr' ){
    //         return {
    //             ...oldState,
    //             str: val
    //         };
    //     }
    // }, {
    //     count: 0,
    //     str: '初始值'
    // });

    return <div>
        <Provider value={ {$store, dispatch} }>
            {props.children}
        </Provider>
    </div>
}

const Test3 = ()=> {
    return <Store>
        <Text31/>
    </Store>
}
export default Test3;

